# -*- coding: utf-8 -*-
'''
Copyright(C) 2013 "Kevin Xu <ssonxu@gmail.com>"

This file is part of acqu-center.

acqu-center is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

acqu-center is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with acqu-center.  If not, see <http://www.gnu.org/licenses/>.
'''
import webapp2
import logging
from google.appengine.api import xmpp
from google.appengine.ext.webapp import xmpp_handlers
from modules.box import Box
from modules.contact import Contact as Con
from modules.Predef import Predef as PRE
import modules.Predef 

class xmppHandler(xmpp_handlers.CommandHandler):

    def subscribe(self, message, ll, Sub=True):
        sender = PRE.bare_jid(self.request.get('from'))
        logging.info(sender)
        user = Con.getCon(sender)
        if user is None:
            message.reply(PRE.MESSAGE_NOFOUNDUSER)
            return
        
        log = []
        for label in ll.split():

            if label and len(label)>0:
                i = PRE.atoi(label)
                if i>=0:
                    b = Box.getBoxByID(i)
                else:
                    b = Box.getBox(label)

                if b is not None:
                    if Sub and (b.ID() not in user.subs):
                        user.subs.append(b.ID())
                        user.put()
                        log.append("You have subscribed {}".format(label))
                    elif not Sub and (b.ID() in user.subs) :
                        user.subs.remove(b.ID())
                        user.put()
                        log.append("You have unsubscribed {}".format(label))

        # list subscribe information
        log.append('-----------------------')
        out = u'\n'.join(log)
        co = []
        for s in user.subs:
            b = Box.getBoxByID(s)
            if( b is not None and b in Box.listBoxes(Running=True) ):
                co.append(u"{}.{} - {}".format(s, b.label, b.description))
        if len(co)>0:
            out = u'\n'.join([out,PRE.MESSAGE_SUBS.format(u"\n\n".join(co))])
        else:
            out = u'\n'.join([out,PRE.MESSAGE_NOSUBS])

        message.reply(out)


    def processing(self, message, ll):
        co = []
        for label in ll.split():
            i = PRE.atoi(label)
            if i>=0:
                b = Box.getBoxByID(i)
            else:
                b = Box.getBox(label)

            if b is not None:
                report=b.report(isSkipMatch=True)
                if  len(report)>0:
                    co.append(report)
            else:
                co.append(PRE.MESSAGE_NOFOUND.format(label))

        if len(co)>0:
            message.reply(u'\n'.join(co))
        else:
            message.reply(PRE.MESSAGE_MENU.format(Box.getMenu()))

    def unhandled_command(self, message=None):
        logging.info("unhandled_command")
        message.reply(PRE.MESSAGE_UNHANDLED,raw_xml=False)

    def text_message(self, message=None):
        logging.info("text_message")
        self.processing( message, message.body.strip() )

    def menu_command(self, message=None):
        logging.info("menu_command")
        message.reply(PRE.MESSAGE_MENU.format(Box.getMenu()))

    def ask_command(self, message=None):
        label=message.body[5:]
        self.processing( message, label )

    def unsub_command(self, message=None):
        label=message.body[7:]
        self.subscribe( message, label, Sub=False )

    def sub_command(self, message=None):
        label=message.body[5:]
        self.subscribe( message, label )

    def help_command(self, message=None):
        logging.info("help_command")
        message.reply(PRE.MESSAGE_HELP,raw_xml=False)

class xmppSubscribedHandler(webapp2.RequestHandler):
    def post(self,status):
        sender = PRE.bare_jid(self.request.get('from'))
        logging.info(status)
        Con.addUser(sender)
        xmpp.send_message(
                sender,
                PRE.MESSAGE_HELLO)

app = webapp2.WSGIApplication([
    ('/_ah/xmpp/message/chat/', xmppHandler),
    ('/_ah/xmpp/subscription/(subscribe|subscribed)/', xmppSubscribedHandler),
    ], debug=True)
    #('/_ah/xmpp/presence/(available|unavailable)/', xmppPresenceHandler),

#class xmppPresenceHandler(webapp2.RequestHandler):
#    def post(self,status):
#        sender = PRE.bare_jid(self.request.get('from'))
#        if status == 'available':
#            xmpp.send_message(
#                    sender,
#                    PRE.MESSAGE_HELLO)
